package com.zhenghaijin.recommendationservice.controller;

import com.zhenghaijin.recommendationservice.model.ApiResponse;
import com.zhenghaijin.recommendationservice.model.UserBehavior;
import com.zhenghaijin.recommendationservice.service.RecommendationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/recommendations")
public class RecommendationController {

    private static final Logger logger = LoggerFactory.getLogger(RecommendationController.class);

    @Autowired
    private RecommendationService recommendationService;

    // 提交用户行为，使用 POST 方法，表示创建一个新资源
    @PostMapping
    public ApiResponse<String> submitBehavior(@RequestBody UserBehavior behavior) {
        logger.info("收到用户行为提交请求: {}", behavior);
        recommendationService.saveUserBehavior(behavior);
        logger.info("用户行为已记录: {}");
        return ApiResponse.success("行为已记录");
    }

    // 获取用户的推荐列表，使用 GET 方法，表示获取资源
    @GetMapping("/{userId}")
    public ApiResponse<Page<Long>> getRecommendations(@PathVariable Long userId,
                                                      @RequestParam(defaultValue = "0") int page,
                                                      @RequestParam(defaultValue = "10") int size) {
        logger.info("收到推荐列表获取请求, 用户ID: {}, 分页参数: page={}, size={}", userId, page, size);
        Pageable pageable = PageRequest.of(page, size);
        Page<Long> recommendations = recommendationService.getRecommendations(userId, pageable);
        logger.info("返回推荐结果数量: {}", recommendations.getSize());
        return ApiResponse.success(recommendations);
    }

    // 刷新推荐结果，使用 PUT 方法，表示更新资源
    @PutMapping("/refresh")
    public ApiResponse<String> refresh() {
        logger.info("收到推荐结果刷新请求");
        recommendationService.refreshRecommendations();
        logger.info("推荐结果已成功刷新");
        return ApiResponse.success("推荐结果已刷新");
    }
}